package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //1.从session中获取员工id，判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        //2.员工登录
        if (empId != null) {
            BaseContext.setCurrentId(empId);
            return true;
        }
        //1.从session中获取用户id，判断用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        //2.用户登录
        if (userId != null) {
            BaseContext.setCurrentId(userId);
            return true;
        }
        //3.说明员工未登录，响应数据给前端code=0 msg=NOTLOGIN
        R r = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(r));
        return false;
    }
}
